package com.azzcs.catalina.mapper;

import com.azzcs.catalina.context.Context;
import com.azzcs.catalina.host.Host;
import com.azzcs.catalina.wrapper.Wrapper;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wzg
 * @Date: 2021/1/9 下午8:22
 * mapper 是存储了所有的 host、content、wrapper
 * 并按照顺序排好，然后在查找时进行二分查找
 */
public class Mapper {

    private List<MappedHost> hosts = new ArrayList<>();

    public void addHost(String name,Host host){
        hosts.add(new MappedHost(name,host));
    }

    public MappedHost getHost(String name){
        for (MappedHost host : hosts) {
            if(host.name.trim().equals(name.trim())){
                return host;
            }
        }
        return null;
    }

    public void addContext(MappedHost mappedHost,String name,Context context){
        mappedHost.contexts.add(new MappedContext(name,context));
    }

    public MappedContext getContext(MappedHost mappedHost,String name){
        List<MappedContext> contexts = mappedHost.contexts;
        for (MappedContext context : contexts) {
            if(context.name.trim().equals(name.trim())){
                return context;
            }
        }
        return null;
    }

    public void addWrapper(MappedContext mappedContext,String name,Wrapper wrapper){
        mappedContext.wrappers.add(new MappedWrapper(name,wrapper));
    }

    public MappedWrapper getWrapper(MappedContext mappedContext,String name){
        List<MappedWrapper> wrappers = mappedContext.wrappers;
        for (MappedWrapper wrapper : wrappers) {
            String wrapperName = "/"+wrapper.name.trim();
            if(wrapperName.startsWith(name)){
                return wrapper;
            }
        }
        return null;
    }
    public class MappedHost extends MapElement<Host>{

        public List<MappedContext> contexts = new ArrayList<>();

        public MappedHost(String name, Host obj) {
            super(name, obj);
        }
    }

    public class MappedContext extends MapElement<Context>{
        public List<MappedWrapper> wrappers = new ArrayList<>();
        public MappedContext(String name, Context obj) {
            super(name, obj);
        }
    }

    public class MappedWrapper extends MapElement<Wrapper>{

        public MappedWrapper(String name, Wrapper obj) {
            super(name, obj);
        }
    }

    class MapElement<T>{
        public final String name;
        public final T obj;

        public MapElement(String name, T obj) {
            this.name = name;
            this.obj = obj;
        }
    }
}
